package com.liu.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        BlogDao blogDao = new BlogDao();
        String param = req.getParameter("blogId");
        if (param == null) {
            List<Blog> blogs = blogDao.selectAll();
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(respJson);
        } else {
            int blogId = Integer.parseInt(param);
            Blog blog = blogDao.selectOne(blogId);
            UserDao userDao = new UserDao();
            DataDao dataDao = new DataDao();
            User user = userDao.selectById(blog.getUserId());
            Data data = dataDao.selectById(blog.getUserId());
            String blogJson = objectMapper.writeValueAsString(blog);
            String userJson = objectMapper.writeValueAsString(user);
            String dataJson = objectMapper.writeValueAsString(data);

            resp.getWriter().write("[" + blogJson + "," + userJson + "," + dataJson + "]");
            System.out.println(1123);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        Blog blog = objectMapper.readValue(req.getInputStream(), Blog.class);
        System.out.println(blog.getContent() + " " + blog.getTitle() + " " + blog.getBlogId() + " " + blog.getUserId() + " " + blog.getCategory());
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.getWriter().write("0");
            return;
        }
        blog.setUserId(((User) session.getAttribute("user")).getUserId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        resp.getWriter().write("1");
    }
}
